<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

<html>
<head>
  <meta name="generator" content=
  "HTML Tidy for Linux/x86 (vers 1 September 2005), see www.w3.org">

  <title>end</title>
  <link href="../cppreference.css" rel="stylesheet" type="text/css">
</head>

<body>
<table>
  <tr>
  <td>
  <div class="body-content">

  <div class="header-box">
    <a href="../index.html">cppreference.com</a> &gt; <a href=
    "index.html">C++ Vectors</a> &gt; <a href="end.html">end</a>
  </div>

  <div class="name-format">
    end
  </div>

  <div class="syntax-name-format">
    Syntax:
  </div>
  <pre class="syntax-box">
  #include &lt;vector&gt;
  iterator end();
  const_iterator end() const;
</pre>

  <p>The end() function returns an iterator just past the end of the
  vector.</p>

  <p>Note that before you can access the last element of the vector
  using an iterator that you get from a call to end(), you&#39;ll have
  to decrement the iterator first.  This is because end() doesn't
  point to the end of the vector; it points <strong>just past the end
  of the vector</strong>.</p>  

  <p>For example, in the following code, the first "cout" statement
  will display garbage, whereas the second statement will actually
  display the last element of the vector:</p>

  <pre class="example-code">
  vector&lt;int&gt; v1;
  v1.push_back( 0 );
  v1.push_back( 1 );
  v1.push_back( 2 );
  v1.push_back( 3 );

  int bad_val = *(v1.end());
  cout &lt;&lt; "bad_val is " &lt;&lt; bad_val &lt;&lt; endl;

  int good_val = *(v1.end() - 1);
  cout &lt;&lt; "good_val is " &lt;&lt; good_val &lt;&lt; endl;
</pre>

  <p>The next example shows how <a href= "begin.html">begin</a>() and
  end() can be used to iterate through all of the members of a
  vector:</p> <pre class="example-code"> vector&lt;int&gt; v1( 5, 789
  ); vector&lt;int&gt;::iterator it; for( it = v1.begin(); it !=
  v1.end(); it++ ) { cout &lt;&lt; *it &lt;&lt; endl; } </pre>

  <p>The iterator is initialized with a call to <a href=
  "begin.html">begin</a>(). After the body of the loop has been
  executed, the iterator is incremented and tested to see if it is
  equal to the result of calling end(). Since end() returns an iterator
  pointing to an element just after the last element of the vector, the
  loop will only stop once all of the elements of the vector have been
  displayed.</p>

  <p>end() runs in <a href="../complexity.html">constant time</a>.</p>

  <div class="related-name-format">
    Related topics:
  </div>

  <div class="related-content">
    <a href="begin.html">begin</a><br>
    <a href="rbegin.html">rbegin</a><br>
    <a href="rend.html">rend</a>
  </div>
  </div>
  </td>
  


  </tr>
  </table>
</body></html>
